package com.gitee.xiao.ai;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.tensorflow.SavedModelBundle;
import org.tensorflow.Session;
import org.tensorflow.Tensor;

import java.util.ArrayList;
import java.util.List;

/**
 * @author wang xiao
 * date 2024/7/10
 */
@RestController
public class RecommendationController {

    private final SavedModelBundle model;

    public RecommendationController() {
        // 加载模型
        this.model = SavedModelBundle.load("/path/to/saved/model");
    }

    @GetMapping("/recommend")
    public List<String> recommend(@RequestParam String userId) {
        // 获取用户历史数据
        List<UserData> userDataList = DataPreprocessing.fetchDataByUserId(userId);

        // 构建输入张量
        Tensor<?> inputTensor = Tensor.create(userDataList);

        // 进行预测
        Session session = model.session();
        List<Tensor<?>> outputs = session.runner().feed("input", inputTensor).fetch("output").run();
        Tensor<String> outputTensor = outputs.get(0).expect(String.class);

        // 解析结果
        List<String> recommendations = new ArrayList<>();
        try (outputTensor) {
            return   outputTensor.copyTo(recommendations);
        }
    }
}
